package com.zb.nio.selector;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.util.Iterator;
import java.util.Set;

/**
 * @author: zhaobin
 * @date: 2024/1/3 21:11
 * @Description:
 */
public class SelectorDemo1 {

    public static void main(String[] args) throws IOException {
        // 创建选择器
        Selector selector = Selector.open();

        // 创建通道
        ServerSocketChannel ssc = ServerSocketChannel.open();

        // 设置通道为非阻塞模式
        ssc.configureBlocking(false);

        // 为通道绑定连接
        ssc.bind(new InetSocketAddress(9999));

        // 将通道注册到选择器，关注接收状态
        ssc.register(selector, SelectionKey.OP_ACCEPT);


        // 查询是否有状态就绪
        //int n = selector.select();
        //int n = selector.select(2000);
        int n = selector.selectNow();
        System.out.println(n);

        // 获取选择键集合
        Set<SelectionKey> selectionKeys = selector.selectedKeys();
        // 遍历选择键集合(1)
        for (SelectionKey key : selectionKeys) {
            if (key.isAcceptable()) {
                // 可接收
                System.out.println("可接收");
            } else if (key.isConnectable()) {
                // 可连接
                System.out.println("可连接");
            } else if (key.isReadable()) {
                // 可读
                System.out.println("可读");
            } else if (key.isWritable()) {
                // 可写
                System.out.println("可写");
            }
        }

        // 遍历选择键集合(2)
        Iterator<SelectionKey> iterator = selectionKeys.iterator();
        while (iterator.hasNext()){
            SelectionKey key = iterator.next();
            if (key.isAcceptable()) {
                // 可接收
                System.out.println("可接收");
            } else if (key.isConnectable()) {
                // 可连接
                System.out.println("可连接");
            } else if (key.isReadable()) {
                // 可读
                System.out.println("可读");
            } else if (key.isWritable()) {
                // 可写
                System.out.println("可写");
            }
            iterator.remove();
        }

    }

}
